﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OBUCare.Core.Models;
using OBUCare.Core.DataAccess;
using Telerik.Web.Mvc;
using OBUCare.Web.Models;
using OBUCare.Web.Infrastructure;
using OBUCare.Core.BL;
using OBUCare.Core.Common;

namespace OBUCare.Web.Controllers
{
    public class RepairOrdersController : Controller
    {
        private OBU_CAREContext db = new OBU_CAREContext();
        ISSUE_RPTContext rptDB = new ISSUE_RPTContext();
        OBUCareOrderMgr obuMgr = new OBUCareOrderMgr();
        UserMgr uMgr = new UserMgr();
        ConfigMgr configMgr = new ConfigMgr();

        #region 原mvc


        //GET: /RepairOrders/

        public ActionResult ParentPage()
        {
            return View();
        }

        //
        // GET: /RepairOrders/Details/5
        /// <summary>
        /// 维修单号
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult RepairOrderDetails(int id = 0)
        {
            RepairDetailsViewModel model = new RepairDetailsViewModel();
            model.OrderTracking = db.REPAIR_ORDER_TRACKING.Where(c => c.REPAIR_ORDER_ID == id).OrderBy(c => c.CREATED_DATE).ToArray();
            UserReceiveObuController obuInfo = new OBUCare.Web.Controllers.UserReceiveObuController();
            //获取报价日期
            REPAIR_ORDER_PRICE orderPrice = db.REPAIR_ORDER_PRICE.Where(c => c.REPAIR_ORDER_ID == id).ToList().FirstOrDefault();
            if (orderPrice != null)
                model.BackDate = orderPrice.BACK_DATE;

            //string orderNo = db.REPAIR_ORDERS.Find(id).REPAIR_ORDER_NO.ToString();
            //string obuNo = db.REPAIR_ORDERS.Find(id).OBU_NO.ToString();
            //model.ObuInfo = obuInfo.getUserObuInfoforOthers(orderNo + "," + obuNo);

            #region 获取标签的维修单信息
            string sqlWhere = " 1=1 ";
            if (id > 0)
                sqlWhere += " AND ID=" + id;

            //根据穿入的ID 获取维修单信息
            View_RepariOrders repairOrders = null;

            var partResult = obuMgr.GetRepairOrders(sqlWhere);

            if (partResult != null && partResult.Count() > 0)
                repairOrders = partResult.FirstOrDefault();

            //标签信息
            OPERATOR OperatorInfo = UIUtility.GetCurrentUser();
            //如果维修单信息存在则获取维修费服务费等信息
            if (repairOrders != null)
            {

                var partsList = db.PARTS_TYPE.ToList();
                //根据维修单性质ID获取维修性质名称
                REPAIR_TYPE repairType = obuMgr.getRepairTypeValueBy(repairOrders.REPAIR_TYPE);
                //根据维修单编号或标签号获取故障点及价格
                var repairFeeList = obuMgr.getRepairFee(repairOrders.ID);
                var repairFee = new List<RepairFeeModel>();

                foreach (var item in repairFeeList)
                {
                    var partsinfo = (from parts in partsList
                                     where parts.ID == item.FAULT_PARTS
                                     select parts).FirstOrDefault();

                    var alllist = new RepairFeeModel() { RepairPrice = item, PartsType = partsinfo };

                    repairFee.Add(alllist);
                }

                var repairFeeAdjust = obuMgr.getRepairFeeAdjust(repairOrders.ID, AdjustType.AdjustRepairFee).ToList();//维修费调整信息


                var serviceFeeAdjust = obuMgr.getRepairFeeAdjust(repairOrders.ID, AdjustType.AdjustServiceFee).ToList();//服务费调整

                var userReceiveInfo = new UserReceiveObuInfo()
                {
                    RepairOrder = repairOrders,
                    RepairType = repairType,
                    RepairFeeModel = repairFee,
                    RepairFeeAdjust = repairFeeAdjust,
                    ServiceFeeAdjust = serviceFeeAdjust

                };
                model.ObuInfo = userReceiveInfo;
            }
            #endregion

            IEnumerable<REPAIR_ORDER_FAULT> repairFault = db.REPAIR_ORDER_FAULT.Where(c => c.REPAIR_ORDER_ID == id).ToList();

            string remark = "";
            foreach (var item in repairFault)
            {
                string faultType = item.FAULT_TYPE.ToString();
                var dictValue = (from i in db.DICT_TYPE_VALUE.Include("DICT_TYPE")
                                 where i.DICT_TYPE.TYPE_CODE == "FaultType" && i.DICT_CODE == faultType
                                 select i).FirstOrDefault();
                if (dictValue != null)
                    remark += dictValue.DICT_TITLE.ToString() + "、";
            }
            if (remark != "")
                model.RepairFaultRemark = remark.Substring(0, remark.Length - 1);

            if (model == null)
            {
                return HttpNotFound();
            }
            return View("RepairOrderDetails", model);
        }

        //
        // GET: /RepairOrders/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /RepairOrders/Create

        [HttpPost]
        public ActionResult Create(REPAIR_ORDERS repair_orders)
        {
            if (ModelState.IsValid)
            {
                db.REPAIR_ORDERS.Add(repair_orders);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(repair_orders);
        }

        //
        // GET: /RepairOrders/Edit/5

        public ActionResult Edit(long id = 0)
        {
            REPAIR_ORDERS repair_orders = db.REPAIR_ORDERS.Find(id);
            if (repair_orders == null)
            {
                return HttpNotFound();
            }
            return View(repair_orders);
        }

        //
        // POST: /RepairOrders/Edit/5

        [HttpPost]
        public ActionResult Edit(REPAIR_ORDERS repair_orders)
        {
            if (ModelState.IsValid)
            {
                db.Entry(repair_orders).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(repair_orders);
        }

        //
        // GET: /RepairOrders/Delete/5

        public ActionResult Delete(long id = 0)
        {
            REPAIR_ORDERS repair_orders = db.REPAIR_ORDERS.Find(id);
            if (repair_orders == null)
            {
                return HttpNotFound();
            }
            return View(repair_orders);
        }

        //
        // POST: /RepairOrders/Delete/5
        [HttpPost]
        public ActionResult DeleteData(string ID, string Remark)
        {
            try
            {
                var repair = db.REPAIR_ORDERS.Find(ID.ToLong());
                if (repair != null && repair.STATUS >= RepairOrderStatus.ReturnedToRepairGroup.ToInt())
                {
                    return Json(new { Success = false, ErrorMsg = "该标签已退回维修组，不允许删除" });
                }
                else
                {
                    int id;
                    if (int.TryParse(ID, out id))
                    {
                        string msg = "";
                        string glRepairs = obuMgr.GetOtherRepair(id);
                        string invoiceInfo = obuMgr.GetOtherInvoice(obuMgr.GetOperationIdByRepairId(id)) ? "此维修单的发票涉及其他业务流水，请重新提交其他流水的发票信息" : "";
                       
                        if (obuMgr.DeleteRepair(id, Remark, UIUtility.GetCurrentUser().OPERATOR_NO, UIUtility.GetCurrentUser().AgentNo, out msg))
                        {                                               
                            return Json(new { Success = true, ErrorMsg = "删除成功" + glRepairs + invoiceInfo });
                        }
                        else
                        {
                            return Json(new { Success = false, ErrorMsg = "删除失败：" + msg });
                        }
                    }
                    else
                    {
                        return Json(new { Success = false, ErrorMsg = "删除失败，ID为非整数" });
                    }

                    //repair.STATUS = -1;
                    //repair.MODIFY_BY = UIUtility.GetCurrentUser().OPERATOR_NO;
                    //repair.MODIFY_DATE = DateTime.Now;
                    //db.SaveChanges();

                }
            }
            catch (Exception ex)
            {
                return Json(new { Success = true, ErrorMsg = "未知错误，请联系管理员" });
            }
        }
        [HttpPost, ActionName("Delete")]
        [GridAction]
        public ActionResult DeleteConfirmed(long id)
        {
            REPAIR_ORDERS repair_orders = db.REPAIR_ORDERS.Find(id);
            //db.REPAIR_ORDERS.Remove(repair_orders);
            repair_orders.REPAIR_TYPE = -1;
            db.SaveChanges();
            // return RedirectToAction("Index");
            var allItems = obuMgr.GetRepairOrders();
            IEnumerable<View_RepariOrders> result = null;
            string url = HttpContext.Request.RawUrl;
            int? num = url.Substring(url.LastIndexOf("/") + 1).ToText().ToInt();
            if (num != null)
            {
                result = (from s in allItems
                          where s.STATUS.Equals(num)
                          select s).ToList();
            }
            else
                result = allItems;
            var temp = new GridModel(result);
            return View(temp);
        }

        #endregion



        public ActionResult Index()
        {
            return RedirectToAction("NewOrder");
        }

        public ActionResult EditOrder(long id)
        {
            var orderInfo = obuMgr.GetRepairOrders(" ID=" + id).FirstOrDefault();

            var orderSpecial = db.REPAIR_ORDERS.Where(m => m.ID == id).FirstOrDefault();

            View_OBU_Info obuInfo = new View_OBU_Info();
            obuInfo.OBU_NO = orderInfo.OBU_NO;
            obuInfo.REGISTE_DATE = orderInfo.REGISTER_DATE;
            obuInfo.SPEC_ID = orderSpecial.SPEC_ID;
            obuInfo.SPEC_NAME = orderInfo.SPEC_NAME;
            obuInfo.SUPPLIER_ShortName = orderInfo.SUPPLIER;
            obuInfo.SUPPLIER = orderInfo.SUPPLIER;
            obuInfo.SUPPLIERS_ID = orderInfo.SUPPLIERS_ID;
            obuInfo.USER_NAME = orderInfo.OWNER_NAME;
            obuInfo.USER_NO = orderInfo.USER_NO;
            obuInfo.VEHICLE_CLASS = (short)orderInfo.VEHICLE_CLASS;
            obuInfo.VEHICLE_CLASS_NAME = orderInfo.VEHICLE_CLASS_NAME;
            obuInfo.VEHICLE_PLATE_NO = orderInfo.VEHICLE_PLATE_NO;


            var info = new ObuInfo() { ObuBaseInfo = obuInfo, OperatorInfo = UIUtility.GetCurrentUser() };
            ViewBag.ObuInfo = info;
            var mm = getFaultViewModel();

            ViewBag.FaultViewModel = mm;
            ViewBag.RepairTypeViewModel = getRepairType();
            //REPAIR_ORDERS order = db.REPAIR_ORDERS.Where(m => m.OBU_NO == id).OrderBy(m => m.ID).FirstOrDefault();
            IQueryable<REPAIR_ORDER_FAULT> type = db.REPAIR_ORDER_FAULT.Where(m => m.REPAIR_ORDER_ID == id);
            //ViewBag.ID = order.ID;
            string fault = string.Empty;
            string faultTxt = string.Empty;
            bool faceStatus = true;
            if (id != null)
            {
                foreach (var item in type)
                {
                    fault += item.FAULT_TYPE + ",";
                    if (!item.REMARK.IsNullOrEmpty())
                    {
                        faultTxt = item.REMARK;
                    }
                }
                if (fault.Length != 0)
                {
                    fault = fault.Substring(0, fault.Length - 1);
                }
                faceStatus = orderSpecial.FACE_STATUS;
            }
            ViewBag.FaultTxt = faultTxt;
            ViewBag.FaultType = fault;
            ViewBag.FaceStatus = faceStatus;
            return View("EditOrder", orderSpecial);
        }


        [HttpPost]
        public ActionResult EditOrder(REPAIR_ORDERS repair_orders, string orderFaultReMark, DateTime REPORT_DATE_UI)
        {
            try
            {
                repair_orders.REPORT_DATE = REPORT_DATE_UI;
                //repair_orders.SPARE_OBU_ISSUE_DATE = SPARE_OBU_ISSUE_DATE_UI;
                string spare_obu_issue_date = Request["SPARE_OBU_ISSUE_DATE_UI"];
                if (!spare_obu_issue_date.IsNullOrEmpty())
                {
                    repair_orders.SPARE_OBU_ISSUE_DATE = DateTime.Parse(spare_obu_issue_date);
                }
                if (ModelState.IsValid)
                {
                    //REPAIR_ORDERS order = db.REPAIR_ORDERS.Where(m => m.OBU_NO == repair_orders.OBU_NO).OrderBy(m => m.ID).FirstOrDefault();//不知道哪里赋值了，得到的ID始终是OBUID，所以保存不到数据库，目前先这么操作
                    //repair_orders.ID = order.ID;
                    var u = UIUtility.GetCurrentUser();
                    var fautls = getFaultInfos(orderFaultReMark);
                    string agentno = "";
                    string ip = "";
                    if (Request["Agent"] != null)
                    {
                        agentno = Request["Agent"];
                        ip = rptDB.GetAgentByNo(agentno) == null ? u.CLIENT_IP : rptDB.GetAgentByNo(agentno).ClientIP;
                    }
                    obuMgr.AlterRepariOrder(repair_orders, fautls, u, agentno, ip);
                    return Content("<Script>alert('修改成功！');window.location.href='/RepairOrders/List/';</Script>");
                    //return RedirectToAction("Index");
                }
                return Content("<Script>alert('修改失败！');</Script>");
                //return RedirectToAction("NewOrder");
            }
            catch (Exception e)
            {
                var msg = e.Message;
                return Content("<Script>alert('修改失败!');</Script>");
                //return RedirectToAction("Index");
            }
        }


        public ActionResult NewOrderWithNoBaseInfo(string id)
        {
            REPAIR_ORDERS order = null;
            string fault = string.Empty;
            string faultTxt = string.Empty;
            var m = getFaultViewModel();
            string actionName = "NewOrderWithNoBaseInfo";
            if (id != null)
            {
                order = db.REPAIR_ORDERS.ToList().Where(s => s.ID == id.ToLong()).FirstOrDefault();
                IQueryable<REPAIR_ORDER_FAULT> type = db.REPAIR_ORDER_FAULT.Where(s => s.REPAIR_ORDER_ID == order.ID);

                foreach (var item in type)
                {
                    fault += item.FAULT_TYPE + ",";
                    if (!item.REMARK.IsNullOrEmpty())
                    {
                        faultTxt = item.REMARK;
                    }
                }
                if (fault.Length != 0)
                {
                    fault = fault.Substring(0, fault.Length - 1);
                }
                actionName = "EditNewOrderWithNoBaseInfo";
            }
            ViewBag.ActionName = actionName;
            ViewBag.FaultTxt = faultTxt;
            ViewBag.FaultType = fault;
            ViewBag.FaultViewModel = m;
            ViewBag.RepairTypeViewModel = getRepairType();
            return View(order);
        }

        [HttpPost]
        public ActionResult EditNewOrderWithNoBaseInfo(REPAIR_ORDERS repair_orders, string orderFaultReMark, DateTime REPORT_DATE_UI, DateTime REGISTER_DATE_UI)
        {
            try
            {
                repair_orders.REPORT_DATE = REPORT_DATE_UI;
                repair_orders.REGISTER_DATE = REGISTER_DATE_UI;
                string spare_obu_issue_date = Request["SPARE_OBU_ISSUE_DATE_UI"];
                if (!spare_obu_issue_date.IsNullOrEmpty())
                {
                    repair_orders.SPARE_OBU_ISSUE_DATE = DateTime.Parse(spare_obu_issue_date);
                }
                string supplier = Request["Supplier"];
                if (supplier != null)
                {
                    int id = int.Parse(supplier);
                    repair_orders.SUPPLIER_ID = id;
                    repair_orders.SUPPLIER = db.SUPPLIERS.Where(m => m.ID == id).Select(m => m.NAME).FirstOrDefault();
                }
                string specs = Request["Specs"];
                if (specs != null)
                {
                    int id = int.Parse(specs);
                    repair_orders.SPEC_ID = id;
                    repair_orders.SPEC_NAME = db.SPECS.Where(m => m.ID == id).Select(m => m.SPEC_NAME).FirstOrDefault();
                }
                if (ModelState.IsValid)
                {
                    var u = UIUtility.GetCurrentUser();
                    var fautls = getFaultInfos(orderFaultReMark);
                    string agentno = "";
                    string ip = "";
                    if (Request["Agent"] != null)
                    {
                        agentno = Request["Agent"];
                        ip = rptDB.GetAgentByNo(agentno) == null ? u.CLIENT_IP : rptDB.GetAgentByNo(agentno).ClientIP;
                    }
                    obuMgr.AlterRepariOrder(repair_orders, fautls, u, agentno, ip);

                    ////如果有备签及押金 则跳转至流水单管理
                    //if (repair_orders.SPARE_OBU_NO != null && repair_orders.SPARE_OBU_PRICE > 0)
                    //{
                    //    string url = "/Transaction/Index/?orderUserNo=" + repair_orders.USER_NO;
                    //    return Content("<Script>alert('修改成功！');window.location.href='" + url + "';</Script>");
                    //}
                    return Content("<Script>alert('修改成功！');window.location.href='/RepairOrders/List/';</Script>");
                }
                return Content("<Script>alert('修改失败！');window.location.href='/RepairOrders/NewOrder/';</Script>");
            }
            catch (Exception e)
            {
                var msg = e.Message;
                return Content("<Script>alert('修改失败!');window.location.href='/RepairOrders/NewOrder/';</Script>");
                //return RedirectToAction("Index");
            }
        }

        [HttpPost]
        public ActionResult NewOrderWithNoBaseInfo(REPAIR_ORDERS repair_orders, string orderFaultReMark)
        {
            try
            {
                bool flag = checkExitObuRepair(repair_orders.OBU_NO);
                if (flag == false)
                    return Json(new { id = -1, userNO = "", Success = false, ErrorMsg = "该标签号已有维修单信息，流程未结束，不允许再次录入！" });
                var u = UIUtility.GetCurrentUser();

                //如果备签选择的否 则备签价格和日期为null
                if (Request["radisNeedSpareObu"] != null && Request["radisNeedSpareObu"].ToString() == "0")
                {
                    repair_orders.SPARE_OBU_PRICE = null;
                    repair_orders.SPARE_OBU_ISSUE_DATE = null;
                }

                string ip = "";

                string register_date = Request["REGISTER_DATE_UI"];
                if (!register_date.IsNullOrEmpty())
                {
                    repair_orders.REGISTER_DATE = Convert.ToDateTime(register_date);
                }
                string report_date_ui = Request["REPORT_DATE_UI"];
                if (!report_date_ui.IsNullOrEmpty())
                {
                    repair_orders.REPORT_DATE = Convert.ToDateTime(report_date_ui);
                }
                string spare_obu_issue_date = Request["SPARE_OBU_ISSUE_DATE_UI"];
                if (!spare_obu_issue_date.IsNullOrEmpty())
                {
                    repair_orders.SPARE_OBU_ISSUE_DATE = DateTime.Parse(spare_obu_issue_date);
                }
                string supplier = Request["Supplier"];
                if (supplier != null)
                {
                    int id = int.Parse(supplier);
                    repair_orders.SUPPLIER_ID = id;
                    repair_orders.SUPPLIER = db.SUPPLIERS.Where(m => m.ID == id).Select(m => m.NAME).FirstOrDefault();
                }
                string specs = Request["Specs"];
                if (specs != null)
                {
                    int id = int.Parse(specs);
                    repair_orders.SPEC_ID = id;
                    repair_orders.SPEC_NAME = db.SPECS.Where(m => m.ID == id).Select(m => m.SPEC_NAME).FirstOrDefault();
                }
                string agent = string.Empty;
                if (Request["AgentNo"] == "")
                {
                    agent = Request["Agent"];
                    ip = u.CLIENT_IP;

                }
                else
                {
                    agent = Request["AgentNo"];
                    ip = rptDB.GetAgentByNo(agent) == null ? u.CLIENT_IP : rptDB.GetAgentByNo(agent).ClientIP;
                }
                if (ModelState.IsValid)
                {
                    var fautls = getFaultInfos(orderFaultReMark);

                    repair_orders.ORDER_TYPE = 1;//0为正常录入 1 为补录
                    obuMgr.NewRepariOrder(repair_orders, fautls, u, agent, ip);

                    //如果有押金 则跳转至流水单管理  Agent
                    if (repair_orders.SPARE_OBU_PRICE > 0)
                    {
                        return Json(new { id = repair_orders.ID, userNO = repair_orders.USER_NO, Success = true, ErrorMsg = "" });
                    }
                    return Json(new { id = repair_orders.ID, userNO = "", Success = true, ErrorMsg = "" });
                }
                return Json(new { id = -1, userNO = "", Success = false, ErrorMsg = "添加失败！" });
            }
            catch (Exception e)
            {
                return Json(new { id = -1, userNO = "", Success = false, ErrorMsg = e.Message });
            }
        }
        /// <summary>
        /// 根据维修单状态，返回维修单，为空则返回全部
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>     
        public ActionResult List(RepairOrderStatus? id)
        {
            //记录当前默认筛选的状态
            ViewBag.RepairOrderStatus = id.HasValue ? id.ToInt().ToText() : UIConstants.AllItems;
            ViewData["SupplierShortName"] = new ObuDropDownListHlper().GetSuppliersShortName(UIConstants.AllItems, true, new KeyValuePair<string, string>(UIConstants.AllItems, UIConstants.AllItems));

            string sql = "";
            if (id.HasValue && id > 0)
            {
                if (id == RepairOrderStatus.SupplierReturnedRepariPrice)
                {
                    sql = "STATUS IN (" + id.ToInt().ToText() + "," + RepairOrderStatus.ConnectionWithoutCustomers.ToInt().ToText() + ")";
                }
                else if (id == RepairOrderStatus.ReadyForInformCustomer)
                {
                    sql = "STATUS IN (" + id.ToInt().ToText() + "," + RepairOrderStatus.InformedWithoutCustomer.ToInt().ToText() + ")";
                }
                else
                    sql = "STATUS=" + id.ToInt().ToText();
            }
            ViewBag.Sql = sql;
            return View("Index");
        }

        /// <summary>
        /// 根据维修单状态，返回维修单，为空则返回全部
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [GridAction]
        public ActionResult ListItems(RepairOrderStatus? id)
        {
            var allItems = obuMgr.GetRepairOrders();
            IEnumerable<View_RepariOrders> result = null;

            if (id.HasValue && id > 0)
            {
                int status = id.Value.ToInt().Value;

                result = (from s in allItems
                          where s.STATUS.Equals(status)
                          select s).ToList();
            }
            else
                result = allItems;
            var temp = new GridModel(result);
            return View(temp);
        }

        public ActionResult NewOrder()
        {
            var m = getFaultViewModel();
            ViewBag.FaultViewModel = m;
            ViewBag.RepairTypeViewModel = getRepairType();
            return View();
        }

        [HttpPost]
        public ActionResult NewOrder(REPAIR_ORDERS repair_orders, string orderFaultReMark)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    bool flag = checkExitObuRepair(repair_orders.OBU_NO);
                    if (flag == false)
                        return Json(new { id = -1, userNO = "", Success = false, ErrorMsg = "该标签号已有维修单信息，流程未结束，不允许再次录入！" });

                    //如果备签选择的否 则备签价格和日期为null
                    if (Request["radisNeedSpareObu"] != null && Request["radisNeedSpareObu"].ToString() == "0")
                    {
                        repair_orders.SPARE_OBU_PRICE = null;
                        repair_orders.SPARE_OBU_ISSUE_DATE = null;
                    }
                    var u = UIUtility.GetCurrentUser();
                    repair_orders.ORDER_TYPE = repair_orders.SUPPLIER == null ? 1 : 0;//0为正常录入 1为补录
                    var fautls = getFaultInfos(orderFaultReMark);
                    string supplier = Request["Supplier"];
                    string supplierID = Request["SUPPLIER_ID"];
                    string specID = Request["SPEC_ID"];
                    repair_orders.SUPPLIER_ID = Convert.ToInt16(supplierID);
                    repair_orders.SPEC_ID = Convert.ToInt16(specID);
                    if (supplier.Contains(',') != false)
                    {
                        supplier = supplier.Substring(1);
                        int id = int.Parse(supplier);
                        repair_orders.SUPPLIER_ID = id;
                        repair_orders.SUPPLIER = db.SUPPLIERS.Where(m => m.ID == id).Select(m => m.NAME).FirstOrDefault();
                    }
                    string specs = Request["Specs"];
                    if (specs != null)
                    {
                        int id = int.Parse(specs);
                        repair_orders.SPEC_ID = id;
                        repair_orders.SPEC_NAME = db.SPECS.Where(m => m.ID == id).Select(m => m.SPEC_NAME).FirstOrDefault();
                    }
                    string agentno = "";
                    string ip = "";
                    if (Request["Agent"] != null)
                    {
                        agentno = Request["Agent"];
                        ip = rptDB.GetAgentByNo(agentno).ClientIP;
                    }
                    obuMgr.NewRepariOrder(repair_orders, fautls, u, agentno, ip);

                    //如果有押金 则跳转至流水单管理
                    if (repair_orders.SPARE_OBU_PRICE > 0)
                    {
                        return Json(new { id = repair_orders.ID, userNO = repair_orders.USER_NO, Success = true, ErrorMsg = "" });
                    }
                    return Json(new { id = repair_orders.ID, userNO = "", Success = true, ErrorMsg = "" });
                }
                return Json(new { id = -1, userNO = "", Success = false, ErrorMsg = "添加失败！" }); //Content("<Script>alert('添加失败！');window.location.href='/RepairOrders/NewOrder/';</Script>");
            }
            catch (Exception ex)
            {
                return Json(new { id = -1, userNO = "", Success = false, ErrorMsg = ex.Message });
            }
        }

        /// <summary>
        /// 从表单中获取故障描述
        /// </summary>
        /// <returns></returns>
        private IList<REPAIR_ORDER_FAULT> getFaultInfos(string orderFaultReMark)
        {
            DICT_TYPE_VALUE otherFault = configMgr.GetTypeValue(ConfigMgr.tblFaultType, ConfigMgr.tblFaultType_Other);
            var form = Request.Form;
            List<REPAIR_ORDER_FAULT> list = new List<REPAIR_ORDER_FAULT>();
            form.AllKeys.Each(k =>
            {
                if (k.StartsWith(UIConstants.orderFault))
                {
                    bool check = Request.GetCheckBoxValue(k);
                    if (check)
                    {
                        REPAIR_ORDER_FAULT f = new REPAIR_ORDER_FAULT();
                        int id = k.Replace(UIConstants.orderFault, "").ToInt().Value;

                        f.FAULT_TYPE = id;

                        //如果故障描述为其它
                        if (id.ToString().Equals(otherFault.DICT_CODE))
                        {
                            f.REMARK = orderFaultReMark;
                        }

                        list.Add(f);
                    }
                }
            });

            return list;
        }

        /// <summary>
        /// 预览或查看维修单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult PreviewOrder(long id)
        {
            var order = this.obuMgr.GetRepairOrder(id);

            RepairOrderViewModel viewModel = new RepairOrderViewModel(order);

            var obuInfo = getObuInfo(viewModel.OBU_NO);

            viewModel.AGENT_Name = uMgr.GetAgentInfo(viewModel.AGENT_NO).AgentName;

            viewModel.REPAIR_TYPE_Text = configMgr.GetTypeValue(viewModel.REPAIR_TYPE).DICT_TITLE;

            ViewBag.FaultViewModel = getFaults(viewModel.ID);

            return View(viewModel);
        }

        /// <summary>
        /// 确认是否维修
        /// </summary>
        /// <param name="strIDs"></param>
        /// <param name="TransferType"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ConfirmWhetherToRepair(string strIDs, ConfirmRepairedStatus repair)
        {
            bool success = false;
            string message = null;

            try
            {
                var u = UIUtility.GetCurrentUser();
                var idList = strIDs.Split(',').ConvertTo(s => s.ToLong().Value);
                success = obuMgr.ConfirmWhetherToRepair(idList, repair, UIUtility.GetCurrentUser());
            }
            catch (Exception ex)
            {
                success = false;
                message = ex.Message;
            }

            return Json(new { success = success, message = message });
        }

        /// <summary>
        /// 通知厂商维修
        /// </summary>
        /// <param name="strIDs"></param>
        /// <param name="TransferType"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InformeSupplierToRepair(string strIDs)
        {
            bool success = false;
            string message = null;

            try
            {
                var u = UIUtility.GetCurrentUser();
                var idList = strIDs.Split(',').ConvertTo(s => s.ToLong().Value);
                success = obuMgr.InformeSupplierToRepair(idList, UIUtility.GetCurrentUser());
            }
            catch (Exception ex)
            {
                success = false;
                message = ex.Message;
            }

            return Json(new { success = success, message = message });
        }

        /// <summary>
        /// 通知用户领取标签
        /// </summary>
        /// <param name="strIDs"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InformeCustomerToGetBack(string strIDs)
        {
            bool success = false;
            string message = null;

            try
            {
                var u = UIUtility.GetCurrentUser();
                var idList = strIDs.Split(',').ConvertTo(s => s.ToLong().Value);
                success = obuMgr.InformeCustomerToGetBack(idList, UIUtility.GetCurrentUser());
            }
            catch (Exception ex)
            {
                success = false;
                message = ex.Message;
            }

            return Json(new { success = success, message = message });
        }

        /// <summary>
        /// 未联系上用户领取标签
        /// </summary>
        /// <param name="strIDs"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InformeWithoutCustomerToGetBack(string strIDs)
        {
            IList<REPAIR_ORDERS> Ilist = new List<REPAIR_ORDERS>();
            bool success = false;
            string message = "";

            try
            {
                var u = UIUtility.GetCurrentUser();
                var idList = strIDs.Split(',').ConvertTo(s => s.ToLong().Value);
                Ilist = obuMgr.InformeWithoutCustomerToGetBack(idList, UIUtility.GetCurrentUser());
                success = true;
                //if (Ilist.Count > 0)
                //{
                //    message += "以下维修单在24小时以内无法提交：";
                //    foreach (var repairorder in Ilist)
                //    {
                //        message += repairorder.REPAIR_ORDER_NO + "；";
                //    }
                //}
            }
            catch (Exception ex)
            {
                success = false;
                message = ex.Message;
            }
            return Json(new { success = success, message = message });
        }

        /// <summary>
        /// 未联系上客户
        /// </summary>
        /// <param name="strIDs"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ConnectionWithoutCustomer(string strIDs)
        {
            IList<REPAIR_ORDERS> Ilist = null;
            bool success = false;
            string message = "";
            try
            {
                var u = UIUtility.GetCurrentUser();
                var idList = strIDs.Split(',').ConvertTo(s => s.ToLong().Value);
                //success = obuMgr.ConnectionCustomers(idList, UIUtility.GetCurrentUser());
                Ilist = obuMgr.ConnectionCustomers(idList, UIUtility.GetCurrentUser());
                success = true;
                if (Ilist.Count > 0)
                {
                    message += "以下维修单在24小时以内无法提交：";
                    foreach (var repairorder in Ilist)
                    {
                        message += repairorder.REPAIR_ORDER_NO + "；";
                    }
                }
            }
            catch (Exception ex)
            {
                success = false;
                message = ex.Message;
            }
            return Json(new { success = success, message = message });
        }

        /// <summary>
        /// 关闭维修单
        /// </summary>
        /// <param name="strIDs"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CloseRepariOrder(string strIDs)
        {
            bool success = false;
            string message = null;

            try
            {
                var u = UIUtility.GetCurrentUser();
                var idList = strIDs.Split(',').ConvertTo(s => s.ToLong().Value);
                success = obuMgr.CloseRepariOrder(idList, UIUtility.GetCurrentUser());
            }
            catch (Exception ex)
            {
                success = false;
                message = ex.Message;
            }

            return Json(new { success = success, message = message });
        }

        /// <summary>
        /// 判断维修单状态是否可修改
        /// </summary>
        /// <param name="strIDs"></param>
        /// <returns></returns>
        public ActionResult checkChangeValid(string TransferType, string strIDs)
        {
            bool success = false;
            string message = "";

            try
            {
                //var idList = strIDs.Split(',').ConvertTo(s => s.ToLong().Value);
                var idList = strIDs.Split(',');
                for (int i = 0; i < idList.Length; i++)
                {
                    idList[i] = idList[i].Substring(0, idList[i].IndexOf('-'));
                }

                var idsList = idList.ConvertTo(s => s.ToLong().Value);
                success = obuMgr.checkStatusIsSame(idsList);
                if (!success)
                    message = "所选中的维修单状态不一致，请重新选择！";
                return Json(new { success = success, message = message });
                //如果是标签返厂商，需要确认厂商是否一致
                if (TransferType == "2")
                    //success = obuMgr.checkSuppliersIsSame(idList);
                    if (!success)
                        message = "所选维修单的厂商不一致，请重新选择！";


            }
            catch (Exception ex)
            {
                success = false;
                message = ex.Message;
            }

            return Json(new { success = success, message = message });
        }
        private IEnumerable<RepairOrderFaultViewModel> getFaults(long orderID)
        {
            var faults = obuMgr.GetRepairOrderFaults(orderID);

            var result = (from f in faults
                          select AutoMapper.Mapper.Map<REPAIR_ORDER_FAULT, RepairOrderFaultViewModel>(f)).ToList();

            result.Each(r =>
                {
                    r.FAULT_TYPE_Text = configMgr.GetTypeValue(r.FAULT_TYPE).DICT_TITLE;
                });

            return result;
        }

        private IEnumerable<RepairOrderViewModel> GetRepairOrders()
        {
            var items = db.REPAIR_ORDERS;
            var results = (from item in items
                           orderby item.CREATED_DATE descending
                           select item).ToList();

            var list = (from c in results
                        select new RepairOrderViewModel(c)).ToList();

            var tblStatus = configMgr.GetTypeValues(ConfigMgr.tblRepairOrderStatus).ToList();

            list.Each(i =>
                {
                    var status = tblStatus.FirstOrDefault(s => s.DICT_CODE.Equals(i.STATUS.ToText()));
                    if (status != null)
                        i.STATUS_Text = status.DICT_TITLE;
                });

            return list;
        }

        public ActionResult TestCheckBoxList(string[] TestCheckBoxList)
        {
            var m = getFaultViewModel();
            return View(m);
        }

        private IEnumerable<ExtendedSelectListItem<DICT_TYPE_VALUE>> getFaultViewModel()
        {
            var allItems = configMgr.GetTypeValues(ConfigMgr.tblFaultType);
            var result = (from s in allItems
                          select new ExtendedSelectListItem<DICT_TYPE_VALUE>() { Value = s.ID.ToText(), Text = s.DICT_TITLE, ExtendedValue = s }).ToList();
            return result;
        }

        private IEnumerable<ExtendedSelectListItem<REPAIR_TYPE>> getRepairType()
        {
            var allItems = db.REPAIR_TYPE.ToList();
            var result = (from s in allItems
                          select new ExtendedSelectListItem<REPAIR_TYPE> { Value = s.ID.ToText(), Text = s.TITLE, ExtendedValue = s }).ToList();
            return result;
        }

        /// <summary>
        /// 用户输入标签号后，动态生成新的标签基本信息控件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ObuBaseInfoControl(string id)
        {
            var info = getObuInfo(id);
            if (info.ObuBaseInfo == null)
                return Content("false");
            return PartialView("ObuBaseInfoControl", info);
        }

        public ActionResult CheckTransferUrl(string obu_no, string id)
        {
            string message = string.Empty;

            var repairOrders = (from i in db.REPAIR_ORDERS.ToList()
                                where i.ID == id.ToLong()
                                select i).FirstOrDefault();
            if (repairOrders != null && repairOrders.ORDER_TYPE == 0)
            {
                message = "true";
            }
            else
            {
                message = "false";
            }
            //var c = uMgr.CheckObuNo(obu_no);
            //if (c != null)
            //{
            //    message = "true";
            //}
            //else
            //{
            //    message = "false";
            //}
            return Json(new { message = message });
        }


        public ActionResult CheckStatus(string id)
        {
            string message = string.Empty;
            //var c = db.REPAIR_ORDERS.ToList().Find(temp => temp.OBU_NO == id);
            var r = (from o in db.REPAIR_ORDERS.ToList()
                     where o.OBU_NO == id
                     select o).ToList();
            if (r != null && r.Count > 0)
            {
                r.Each(c =>
                    {
                        if (c.STATUS == RepairOrderStatus.ClosedWithCustomerPickedBack.ToInt()
                   || c.STATUS == RepairOrderStatus.ClosedWithoutCustomerPickedBack.ToInt()
                            || c.STATUS == DictTypeStatus.Deleted.ToInt())
                        {
                            message = "success";
                        }
                        else
                        {
                            message = "repaired";
                        }
                    });
            }
            else
            {
                message = "success";
            }
            return Json(new { message = message });
        }

        /// <summary>
        /// 根据用户编辑的标签号，动态生成新的标签基本信息控件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ObuBaseInfoControlEdit(string id)
        {
            var info = getObuInfo(id);
            return PartialView("ObuBaseInfoControl", info);
        }


        /// <summary>
        /// 获取OBU对象
        /// </summary>
        /// <param name="obuNo"></param>
        /// <returns></returns>
        private ObuInfo getObuInfo(string obuNo)
        {
            var baseInfo = obuMgr.GetObuInfo(obuNo);
            //根据标签号查询是否有以旧换新的记录，并查出质保期开始时间
            DateTime? registeDate = rptDB.GetRegisteDateByObuNo(obuNo);
            if (registeDate != null)
            {
                baseInfo.REGISTE_DATE = registeDate;
            }
            else
            {
                //得到以旧换翻新更换和回收的之前的标签号
                string lastNo = obuMgr.GetBeaforOldNo(obuNo);
                if (lastNo == null && baseInfo != null)
                {
                    lastNo = baseInfo.LAST_OBU_NO;
                }
                //针对标签的发行时间重新获取，如有标签做过更换，则获取更换前的标签发行时间
                if (baseInfo != null && baseInfo.LAST_OBU_NO != null && baseInfo.LAST_OBU_NO.Trim() != "")
                {
                    //添加判断以旧换翻新的判断逻辑
                    while (true)
                    {
                        var obuInfo = new ISSUE_RPTContext().getRegisteBy(lastNo, baseInfo.USER_NO);
                        if (obuInfo != null)
                        {
                            if (obuInfo.LAST_OBU_NO != null && obuInfo.LAST_OBU_NO.Trim() != "")
                            {
                                //如果还有更换信息，则继续
                                lastNo = obuInfo.LAST_OBU_NO;
                                continue;
                            }
                            else
                            {
                                //如果没有更换信息，则获取最早的发行日期
                                baseInfo.REGISTE_DATE = obuInfo.REGISTE_DATE;
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }

                }
            }

            var info = new ObuInfo() { ObuBaseInfo = baseInfo, OperatorInfo = UIUtility.GetCurrentUser() };
            return info;
        }

        /// <summary>
        /// 获取质保期
        /// </summary>
        /// <param name="obu"></param>
        /// <returns></returns>
        public DateTime GetLifeDate(string obuNo, DateTime? reDate)
        {
            //获取以旧换翻新的日期
            DateTime? date = rptDB.GetDateForOldOfOld(obuNo);
            //如果没有说明是没有以旧换翻新是旧签  就直接是发行日期加上2年
            if (date == null)
            {
                return Convert.ToDateTime(((DateTime)reDate).ToShortDateString()).AddYears(2).AddDays(1);
            }
            else
            {
                //否则，如果有以旧换翻新的日期，进行一下判断
                //如果以旧换翻新的日期大于原质保期内，就是过期后进行的以旧换翻新，
                if ((DateTime)date > ((DateTime)reDate).AddYears(2))
                {
                    //质保期就是以旧换翻新的日期加上三个月
                    return Convert.ToDateTime(((DateTime)date).ToShortDateString()).AddMonths(3).AddDays(1);
                }
                else
                {
                    //如果小于质保期，就按原来的质保期加上3个月
                    return Convert.ToDateTime(((DateTime)reDate).ToShortDateString()).AddYears(2).AddMonths(3).AddDays(1);
                }
            }
        }

        [HttpPost]
        public ActionResult Search(DateTime? FromCreatedDate, DateTime? ToCreatedDate, string RepairOrderNO, string ObuNO,
            string Supplier, string Status, string Agent, string Operator, string IsNeedSpareObu,
            string txtVehicleNo, string txtMobileNo, string ddlConfirmRepaired, string txtOperator) //也可以用这种格式接收参数public ActionResult Search(FormCollection form)
        {
            try
            {
                var sql = obuMgr.GetSearhRepairOrdersSql(FromCreatedDate, ToCreatedDate, RepairOrderNO.Trim().ChangAllTextToNull(),
                    ObuNO.Trim().ChangAllTextToNull(), Supplier.ChangAllTextToNull(), Status.ChangAllTextToNull(),
                    Agent.ChangAllTextToNull(), Operator.ChangAllTextToNull(), IsNeedSpareObu.ChangAllTextToNull(),
                    txtVehicleNo.Trim().ChangAllTextToNull(), txtMobileNo.Trim().ChangAllTextToNull(), ddlConfirmRepaired.ChangAllTextToNull(),
                    txtOperator.Trim().ChangAllTextToNull());

                return Json(new { Sql = sql, Success = true, ErrorMsg = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Sql = "", Success = false, ErrorMsg = ex.Message });
            }
        }



        /// <summary>
        /// 根据维修单状态，返回维修单，为空则返回全部
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [GridAction]
        public ActionResult ListSqlItems(string sql, string searchSql)
        {
            //根据编号判断查询权限
            string whereAgentNo = Request["agentNO"] == null || Request["agentNO"].ToString() == "" ? "" : Request["agentNO"].ToString();
            string modelID = Request["menuNames"] == null || Request["menuNames"].ToString() == "" ? "" : Request["menuNames"].ToString();

            string tempSql = "";
            if ((!sql.IsNullOrEmpty()) && (!searchSql.IsNullOrEmpty()))
                tempSql = sql + " and " + searchSql;
            else
                tempSql = string.Format("{0} {1} ", sql, searchSql);

            whereAgentNo = whereAgentNo == "" ? "" : tempSql.Trim() == "" ? " AGENT_NO='" + whereAgentNo + "'" : " AND AGENT_NO='" + whereAgentNo + "'";

            //如果最小权限为6 则增加操作员查询条件
            OPERATOR operatorInfo = UIUtility.GetCurrentUser();
            string models = UIUtility.getOperatorByModule(operatorInfo, Convert.ToInt32(modelID));
            if (models == "6")
                whereAgentNo += " AND CREATED_BY='" + operatorInfo.OPERATOR_NO + "'";


            var result = obuMgr.GetRepairOrders(tempSql + whereAgentNo);

            var temp = new GridModel(result.OrderByDescending(m => m.MODIFY_DATE));
            return View(temp);
        }

        /// <summary>
        /// 打印维修单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Print(long id, string userNO)
        {
            var order = obuMgr.GetRepairOrders(string.Format("id={0}", id)).FirstOrDefault();

            IList<REPAIR_ORDER_FAULT> faults = (from f in db.REPAIR_ORDER_FAULT
                                                where f.REPAIR_ORDER_ID == id
                                                select f).ToList();

            ViewBag.Faults = faults;
            string url = "/RepairOrders/List/";
            if (!userNO.IsNullOrEmpty())
            {
                url = "/Transaction/Index/?orderUserNo=" + userNO;
            }
            ViewBag.URL = url;
            return View("PrintRepairOrder", order);
        }
        /// <summary>
        /// 判断标签号的维修单信息是否已存在
        /// </summary>
        /// <param name="obu_no"></param>
        /// <returns></returns>
        [HttpPost]
        public bool checkExitObuRepair(string obu_no)
        {
            var exitRepair = (from f in db.REPAIR_ORDERS.ToList()
                              where f.OBU_NO.Equals(obu_no) && f.STATUS != DictTypeStatus.Deleted.ToInt() &&
                              f.STATUS != RepairOrderStatus.ClosedWithCustomerPickedBack.ToInt()
                           && f.STATUS != RepairOrderStatus.ClosedWithoutCustomerPickedBack.ToInt()
                              select f).ToList();
            //var result = (from i in exitRepair
            //              where i.STATUS != RepairOrderStatus.ClosedWithCustomerPickedBack.ToInt()
            //              && i.STATUS != RepairOrderStatus.ClosedWithoutCustomerPickedBack.ToInt()
            //              select i).ToList();
            if (exitRepair != null && exitRepair.Count() > 0)
            {
                return false;
            }
            return true;
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            obuMgr.Dispose();
            configMgr.Dispose();
            uMgr.Dispose();
            base.Dispose(disposing);
        }

        //[HttpPost]
        //public JsonResult _GetOperators(string AgentNo)
        //{

        //    string AgentBy = AgentNo == null ? "" : AgentNo;
        //    OPERATOR operatorInfo = UIUtility.GetCurrentUser();
        //    string requeURL = Request.Url.LocalPath;
        //    string model = UIUtility.getOperatorByModule(operatorInfo, requeURL);
        //    var result = new ObuDropDownListHlper().GetOPERATORSByAgentNo(UIConstants.AllItems, AgentNo, false, new KeyValuePair<string, string>(UIConstants.AllItems, UIConstants.AllItems)).ToList();
        //    switch (model)
        //    {
        //        case "0":
        //        case "3": //如果有所有营业厅和本营业厅负责人的权限 则结果集不变
        //            break;
        //        case "6"://如果为本营业厅操作员的权限 则只绑定自己的名字
        //            SelectListItem cSelect = result.Find(s => s.Value == UIUtility.GetCurrentUser().OPERATOR_NO);
        //            result.Clear();
        //            result.Insert(0, cSelect);
        //            break;
        //        default:
        //            SelectListItem onlySelect = result.Find(s => s.Value == UIUtility.GetCurrentUser().OPERATOR_NO);
        //            result.Clear();
        //            result.Insert(0, onlySelect);
        //            break;

        //    }
        //    return Json(new SelectList(result, "Value", "Text"), JsonRequestBehavior.AllowGet);
        //}



        [HttpPost]
        public JsonResult _GetAgent(string AgentType, string AgentNo)
        {

            string AgentBy = AgentNo == null ? "" : AgentNo;
            var result = new ObuDropDownListHlper().GetAgents(UIConstants.AllItems, false, AgentType, AgentBy,
                 new KeyValuePair<string, string>(UIConstants.AllItems, UIConstants.AllItems)).ToList();
            if (AgentBy == "")
            {
                return Json(new SelectList(result, "Value", "Text"), JsonRequestBehavior.AllowGet);
            }
            else
            {
                SelectListItem cSelect = result.Find(s => s.Value == UIUtility.GetCurrentUser().AgentNo);
                result.Clear();
                result.Insert(0, cSelect);
                return Json(new SelectList(result, "Value", "Text"), JsonRequestBehavior.AllowGet);
            }
            //return Json(new SelectList(result, "Value", "Text"), JsonRequestBehavior.AllowGet);
        }


        [HttpPost]
        public JsonResult _GetAgentReturnIndex(string AgentNo)
        {
            var result = new ObuDropDownListHlper().GetAgents(UIConstants.AllItems, false, "", "").ToList();
            SelectListItem cSelect = result.Find(s => s.Value == AgentNo);
            int index = 0;
            for (int i = 0; i < result.Count; i++)
            {
                if (result[i].Value == AgentNo.Trim())
                {
                    index = i;
                }
            }
            return Json(new { Index = index, Source = new SelectList(result, "Value", "Text") });
        }


        [HttpPost]
        public JsonResult _GetAgentC(string AgentType, string AgentNo)
        {

            string AgentBy = AgentNo == null ? "" : AgentNo;
            var result = new ObuDropDownListHlper().GetAgents(UIConstants.AllItems, false, AgentType, AgentBy,
                 new KeyValuePair<string, string>(UIConstants.AllItems, UIConstants.AllItems)).ToList();
            if (AgentBy == "")
            {
                return Json(new SelectList(result, "Value", "Text"), JsonRequestBehavior.AllowGet);
            }
            else
            {
                SelectListItem cSelect = result.Find(s => s.Value == UIUtility.GetCurrentUser().AgentNo);
                result.Clear();
                result.Insert(0, cSelect);
                return Json(new SelectList(result, "Value", "Text"), JsonRequestBehavior.AllowGet);
            }

        }
        public JsonResult _GetAgentCR(string AgentType, string AgentNo)
        {

            string AgentBy = AgentNo == null ? "" : AgentNo;
            var result = new ObuDropDownListHlper().GetAgents(UIConstants.AllItems, false, AgentType, AgentBy,
                 new KeyValuePair<string, string>(UIConstants.AllItems, UIConstants.AllItems)).ToList();
            if (AgentBy == "")
            {
                result.RemoveAt(0);

                return Json(new SelectList(result, "Value", "Text"), JsonRequestBehavior.AllowGet);
            }
            else
            {
                SelectListItem cSelect = result.Find(s => s.Value == UIUtility.GetCurrentUser().AgentNo);
                result.Clear();
                result.Insert(0, cSelect);
                return Json(new SelectList(result, "Value", "Text"), JsonRequestBehavior.AllowGet);
            }

        }

        /// <summary>
        /// 根据厂商获取型号
        /// </summary>
        /// <param name="Supplier"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult _GetSpecs(string Supplier)
        {
            if (Supplier == "请选择")
            {
                var result = new SelectList("无", "无");
                return Json(new SelectList(result, "Value", "Text"), JsonRequestBehavior.AllowGet);
            }
            else
            {
                int id = Convert.ToInt32(Supplier);
                var result = new ObuDropDownListHlper().GetSpecs(UIConstants.AllItems, false, id).ToList();
                SelectListItem item = new SelectListItem();
                item.Text = "请选择";
                item.Value = "请选择";
                result.Insert(0, item);
                return Json(new SelectList(result, "Value", "Text"), JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        public JsonResult _GetSpecsReturnIndex(string specsID, string supplierID)
        {
            int id = Convert.ToInt32(specsID);
            int supID = Convert.ToInt32(supplierID);
            var result = new ObuDropDownListHlper().GetSpecs(UIConstants.AllItems, false, supID).ToList();
            int index = 0;
            for (int i = 0; i < result.Count; i++)
            {
                if (result[i].Value == specsID)
                {
                    index = i;
                }
            }
            return Json(new { Index = index, Source = new SelectList(result, "Value", "Text") });
        }

        [HttpPost]
        public JsonResult _GetSupplier(string supplierID)
        {
            var result = new ObuDropDownListHlper().GetSuppliers(UIConstants.AllItems, false).ToList();
            int index = 0;
            for (int i = 0; i < result.Count; i++)
            {
                if (result[i].Value == supplierID)
                {
                    index = i;
                }
            }
            return Json(new { Index = index });
        }


        [HttpPost]
        public JsonResult _GetVehicleClass()
        {
            List<SelectListItem> result = new List<SelectListItem>();
            string c = "ABCDE";
            for (int i = 0; i < c.Length; i++)
            {
                SelectListItem item = new SelectListItem();
                item.Text = c[i].ToString();
                item.Value = (i + 1).ToString();
                result.Insert(i, item);
            }
            return Json(new SelectList(result, "Value", "Text"), JsonRequestBehavior.AllowGet);
        }
    }
}

